package com.auto.api.framework.entity;

import com.auto.api.common.utils.JsonMapper;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.Data;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

@Data
public class ReqParamBO implements Serializable {

	public static final Logger logger = LoggerFactory.getLogger(ReqParamBO.class);
		/**
		 * 请求链路ID
		 */
		private String tranId;
		private final JoinPoint point;
		private final Object[] args;

		/**
		 * 执行结果
		 */
		private Object result;
		/**
		 * 执行状态 1-成功,0-失败
		 */
		private Integer status;

		public ReqParamBO(JoinPoint point,  Object[] args) {
			this.point = point;
			this.args = args;
		}

		public String getClassName() {
			return point.getTarget().getClass().getSimpleName();
		}

		public String getMethodName() {
			Signature signature = point.getSignature();
			if (!(signature instanceof MethodSignature)) {
				logger.error("入参: {} ", JsonMapper.toJson(getParamToJson()));
				return "";
			}
			MethodSignature methodSignature = (MethodSignature)signature;
			return methodSignature.getName();
		}

		/**
		 * 过滤不需要json参数
		 * @return Object
		 */
		private Object filterArgs() {
			if (args == null) {
				return null;
			}
			Set params = null;
			for (Object param : args) {
				if (param == null || param instanceof HttpServletRequest
					|| param instanceof HttpServletResponse
					|| param instanceof MultipartFile) {
					continue;
				}
				if (params == null) {
					params = new HashSet();
				}
				params.add(param);
			}
			return params != null && params.size() == 1 ? params.toArray()[0] : params;
		}

		/**
		 * 参数转json
		 * @return String
		 */
		public String getParamToJson() {
			Object params = filterArgs();
        if (params == null) {
            return "";
        }
			try {
				return JsonMapper.toJson(params);
			} catch (Exception ex) {
				logger.error("执行类:{},方法名:{}参数json转换异常", getClassName(), getMethodName());
			}
			return "";
		}

	/**
	 * result转json
	 * @return String
	 */
	public String getResultToJson() {

		if (Objects.isNull(result)) {
			return "";
		}
		try {
			return JsonMapper.toJson(result);
		} catch (Exception ex) {
			logger.error("执行类:{},方法名:{}结果json转换异常", getClassName(), getMethodName());
		}
		return "";
	}
	}